package com.ahy231.service.impl;

import com.ahy231.entity.Transaction;
import com.ahy231.mapper.TransactionMapper;
import com.ahy231.service.TaskService;
import com.ahy231.utils.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Objects;

/**
 * @author ahy231
 * @date 2021/8/6 16:39
 * @description
 */
@Service
public class TaskServiceImpl implements TaskService {

    private final TransactionMapper transactionMapper;

    public TaskServiceImpl(TransactionMapper transactionMapper) {
        this.transactionMapper = transactionMapper;
    }

    @Override
    public Boolean startTask(Long transactionId) {
        Assert.notNull(transactionId, "交易 id 为空");
        Long userId = getUserId();
        Assert.notNull(userId, "service 获取不到用户 id");
        Transaction transaction = transactionMapper.selectOne(new QueryWrapper<Transaction>().eq("transaction_id", transactionId));
        Assert.isTrue(transaction.getStatus() == 3, "交易不是已接受状态");
        Assert.isTrue(Objects.equals(transaction.getUserId(), userId), "不是接单者不能执行订单");
        return transactionMapper.updateById(new Transaction(transactionId, null, null, null, null, null, null, null, 4, null)) > 0;
    }

    @Override
    public Boolean verifyTask(Long transactionId) {
        Assert.notNull(transactionId, "交易 id 为空");
        Long userId = getUserId();
        Assert.notNull(userId, "service 获取不到用户 id");
        Transaction transaction = transactionMapper.selectOne(new QueryWrapper<Transaction>().eq("transaction_id", transactionId));
        Assert.isTrue(transaction.getStatus() == 4, "交易不是执行状态");
        Assert.isTrue(Objects.equals(transaction.getUserId(), userId), "不是接单者不能申请验证");
        return transactionMapper.updateById(new Transaction(transactionId, null, null, null, null, null, null, null, 5, null)) > 0;
    }

    @Override
    public Boolean pass(Long transactionId, Boolean pass) {
        Assert.notNull(transactionId, "交易 id 为空");
        Assert.notNull(pass, "是否通过信息不能为空");
        Long userId = getUserId();
        Assert.notNull(userId, "service 获取不到用户 id");
        Transaction transaction = transactionMapper.selectOne(new QueryWrapper<Transaction>().eq("transaction_id", transactionId));
        Assert.isTrue(transaction.getStatus() == 5, "交易不是申请验证状态");
        Assert.isTrue(Objects.equals(transaction.getUserId(), userId), "不是接单者不能申请验证");
        if (pass) {
            return transactionMapper.updateById(new Transaction(transactionId, null, null, null, null, null, null, null, 6, null)) > 0;
        } else {
            return transactionMapper.updateById(new Transaction(transactionId, null, null, null, null, null, null, null, 4, null)) > 0;
        }
    }

    private Long getUserId() {
        return JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
    }
}
